package tests.read;

import static org.junit.Assert.*;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.BridgeInterface;
import cc.test.bridge.LineInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

public class LineQueryTest01
{
	Budget budget;
	BudgetFactory factory;
	Line line1;
	Line line2;

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        line1 = (Line) budget.createLine();
        line1.setName("Line 1");
		budget.add(line1);
		line2 = (Line) budget.createLine();
		line2.setName("Line 2");
		budget.add(line2);
		budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete(line1, WorkletContext.getInstance());
		Helper.delete(line2, WorkletContext.getInstance());
		Helper.delete(budget, WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		try{
			ArrayList<BasicDBObject> ors = new ArrayList<BasicDBObject>();
			ors.add(new BasicDBObject("entry.name", "Line 1"));
			ors.add(new BasicDBObject("entry.name", "Line 2"));
			BasicDBObject or = new BasicDBObject("$or", ors);
			String criteria = JSON.serialize(or);
			@SuppressWarnings("unchecked")
			ArrayList<BridgeInterface> results =  Helper.query(criteria, WorkletContext.getInstance());
		
			for(BridgeInterface bridge : results){
				if(bridge instanceof LineInterface){
					String name = ((Line) bridge).getName();
					if(!name.equals("Line 1") || !name.equals("Line 2")){
						fail("Line name query for 'Line 1' or 'Line 2' failed");
					}
				}
			}
		}catch(Exception e){
			fail("Line name query failed with exception " + e);
			System.out.println("----------------");
			e.printStackTrace();
		}
	}

}
